package fact.view.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.sql.DataSource;

import fact.view.DTO.UserDTO;


@ManagedBean(name = "userManageBean")
@SessionScoped
public class UserManageBean {

	
	@Resource(name="jdbc/factentry")
	private DataSource ds;
	
	public boolean validateUser(String userId,String password) throws SQLException{
   	 
		boolean response=false;
		if(ds==null)
			throw new SQLException("Can't get data source");
		//get database connection
		Connection con = ds.getConnection();
 
		if(con==null)
			throw new SQLException("Can't get database connection");
 
		PreparedStatement ps = con.prepareStatement("Select count(*) total from MST_USER where userid=? and password=?"); 
 
		ps.setString(1, userId);
		ps.setString(2, password);
		
		//get customer data from database
		ResultSet result =  ps.executeQuery();
 
 
		while(result.next()){
			if(result.getInt("total")>0)
				response=true;
		}
		
 
		return response;
	}
	
	public UserDTO getUserFromUserId(String userId) throws SQLException{
	   	 
		UserDTO userDto=new  UserDTO();
		if(ds==null)
			throw new SQLException("Can't get data source");
		Connection con = ds.getConnection();
 
		if(con==null)
			throw new SQLException("Can't get database connection");
 
		PreparedStatement ps = con.prepareStatement("Select * from MST_USER,MST_ROLE where userid=? AND ISACTIVE=1 " +
													" AND MST_USER.USER_TYPE=MST_ROLE.ROLE_ID "); 
 
		ps.setString(1, userId);
		
		//get customer data from database
		ResultSet result =  ps.executeQuery();
 
 
		if(result.next()){
			userDto.setUserId(result.getString("USERID"));
			userDto.setPassword(result.getString("PASSWORD"));
			userDto.setUserType(result.getString("ROLE_NAME"));
			userDto.setUserName(result.getString("USERNAME"));
			
		}
		
 
		return userDto;
	}
}
